package cn.sstech.member.core.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.sstech.member.config.UrlSetting;
import cn.sstech.member.core.catche.RedisSessionDao;
import cn.sstech.member.core.util.model.Merchant;
import cn.sstech.microservice.token.TokenEntity;

/**
 * 获取由request带入的参数。
 * @author Administrator
 *
 */
public class ConnectionParamProvider {

	RedisSessionDao redisSessionDao;
	UrlSetting urlSetting;
	
	TokenEntity tokenEntity;
	HttpServletRequest request;
	
	Boolean isRegainTokenEntity = true;
	
	public Boolean getIsRegainTokenEntity() {
		return isRegainTokenEntity;
	}
	
	public ConnectionParamProvider(){
		this.redisSessionDao = ApplicationContextHolder.getBean(RedisSessionDao.class);
		this.urlSetting = ApplicationContextHolder.getBean(UrlSetting.class);
		this.request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	Logger logger = LoggerFactory.getLogger(ConnectionParamProvider.class);
	
	public String getSubSystemCode(){
		String subSystemCode = "";
		
		if(null == request){
			return subSystemCode;
		}
		
		//先从cookie中取
		if(null != request.getCookies() && request.getCookies().length > 0){
			List<Cookie> cookies = Arrays.asList(request.getCookies());
			for(Cookie cookie : cookies){
				if(ServiceConstant.SERVICE_IDENTITY_MARK_NAME.equals( cookie.getName())){
					subSystemCode = cookie.getValue();
					break;
				}
			}
		}
		
		//若没有则从header中取
		if("".equals(subSystemCode) || null == subSystemCode){
			String code = request.getHeader(ServiceConstant.SERVICE_IDENTITY_MARK_NAME);
			if(null != code){
				subSystemCode = code;
			}
			else{
				
			}
		}
		
		//若没有则从redis中取。session信息不透明，与用户登录绑定
		if("".equals(subSystemCode) || null == subSystemCode){
			if(null != request.getCookies() && request.getCookies().length > 0){
				String tokenId = "";
				List<Cookie> cookies = Arrays.asList(request.getCookies());
				for(Cookie cookie : cookies){
					if(ServiceConstant.TOKEN_ID_MARK_NAME.equals( cookie.getName())){
						tokenId = cookie.getValue();
						break;
					}
				}
				
				if(!"".equals(tokenId)){
					//用id从redis中取session信息
					try {
						
						TokenEntity tokenEntity = redisSessionDao.getTokenEntity(tokenId);
						if(null != tokenEntity){
							subSystemCode = tokenEntity.getSubSystemCode();
						}
					} catch (Exception e) {
						logger.warn(e.getMessage(),e);
					}
				}
			}
		}

		if(!"".equals(subSystemCode) && null != subSystemCode){
			subSystemCode = subSystemCode+"_";
		}
		
		return subSystemCode;
	}
	
	public String getMngrId(){
		String unionId = "";
		
		if(null == request){
			return unionId;
		}
		
		TokenEntity tokenEntity = getTokenEntity();
		if(null != tokenEntity){
			unionId = tokenEntity.getMngrId();
		}
		
		return unionId;
	}

	private TokenEntity getTokenEntity() {
		TokenEntity tokenEntity = null;
		
		if(!this.getIsRegainTokenEntity()
				&& null != this.tokenEntity){
			return this.tokenEntity;
		}
		
		if(null != request.getCookies() && request.getCookies().length > 0){
			String tokenId = "";
			List<Cookie> cookies = Arrays.asList(request.getCookies());
			for(Cookie cookie : cookies){
				if(ServiceConstant.TOKEN_ID_MARK_NAME.equals( cookie.getName())){
					tokenId = cookie.getValue();
					break;
				}
			}
			
			if(!"".equals(tokenId)){
				//用id从redis中取session信息
				try {
					
					tokenEntity = redisSessionDao.getTokenEntity(tokenId);
				} catch (Exception e) {
					logger.warn(e.getMessage(),e);
				}
			}
		}
		
		if(!this.getIsRegainTokenEntity()){
			this.tokenEntity = tokenEntity;
		}

		return tokenEntity;
	}
	
	
//	protected List<Long> getMerchantIdsByRequest(){
//		List<Long> result = new ArrayList<Long>();
//
//		String userId = this.getUnionId();
//		if(null == userId || "".equals(userId)){
//			return result;
//		}
//		
//		
//		//调用根据用户id获取商户列表接口
//		HttpHeaders headers = new HttpHeaders();
//		Map<String, Object> urlVariables = new HashMap<String, Object>();
//		StringBuilder url = new StringBuilder();
//		url.append(urlSetting.getMenchantService())
//		.append("/api/merchant/merchant/list/")
//		.append(userId);
//		
//		String merchantListStr = RestHttpTemplate.get(url.toString(), headers, urlVariables);
//		JSONObject merchantListJson = null;
//		try {
//			merchantListJson = JSON.parseObject(merchantListStr);
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//			return result;
//		}
//		
//		if(merchantListJson.containsKey("result") && "success".equals(merchantListJson.getString("result"))
//				&& merchantListJson.containsKey("data")){
//			JSONObject data = merchantListJson.getJSONObject("data");
//			
//			if(data.containsKey("list")){
//				List<Merchant> merchantList = JSON.parseArray(data.getString("list")
//						, Merchant.class);
//				
//				if(null != merchantList && !merchantList.isEmpty()){
//					for(Merchant node : merchantList){
//						result.add(node.getId());
//					}
//				}
//			}
//			else{
//				return result;
//			}
//		}
//		
//		return result;
//	}
//	
//	protected List<Long> getMerchantRootIdsByRequest(){
//		List<Long> result = new ArrayList<Long>();
//		
//		String userId = this.getUnionId();
//		if(null == userId || "".equals(userId)){
//			return result;
//		}
//		
//		//调用根据用户id获取商户列表接口
//		HttpHeaders headers = new HttpHeaders();
//		Map<String, Object> urlVariables = new HashMap<String, Object>();
//		StringBuilder url = new StringBuilder();
//		url.append(urlSetting.getMenchantService())
//		.append("/api/merchant/merchant/tree/")
//		.append(userId);
//		
//		String merchantListStr = RestHttpTemplate.get(url.toString(), headers, urlVariables);
//		JSONObject merchantListJson = null;
//		try {
//			merchantListJson = JSON.parseObject(merchantListStr);
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//			return result;
//		}
//		
//		if(merchantListJson.containsKey("result") && "success".equals(merchantListJson.getString("result"))
//				&& merchantListJson.containsKey("data")){
//			JSONObject data = merchantListJson.getJSONObject("data");
//			
//			if(data.containsKey("children")){
//				List<Merchant> merchantList = JSON.parseArray(data.getString("children")
//						, Merchant.class);
//				
//				if(null != merchantList && !merchantList.isEmpty()){
//					for(Merchant node : merchantList){
//						result.add(node.getId());
//					}
//				}
//			}
//			else{
//				return result;
//			}
//		}
//		
//		return result;
//	}
	
	
	public List<Long> getMerchantIdsByRequest() {
		List<Long> result = new ArrayList<Long>();
		String userId = this.getMngrId();
		if (null == userId || "".equals(userId)) {
			return result;
		}

		UrlSetting urlSetting = ApplicationContextHolder.getBean(UrlSetting.class);

		// 调用根据用户id获取商户列表接口
		HttpHeaders headers = new HttpHeaders();
		String subSystemCode = "";
		try {
			subSystemCode = this.getSubSystemCode();
			if(null != subSystemCode && subSystemCode.endsWith("_")){
				subSystemCode = subSystemCode.substring(0, subSystemCode.lastIndexOf("_"));
			}
		} catch (Exception e1) {
			logger.error(e1.getMessage(),e1);
		}
		if(!"".equals(subSystemCode) && null != subSystemCode){
			headers.add("subSystemCode", subSystemCode);
		}
		Map<String, Object> urlVariables = new HashMap<String, Object>();
		StringBuilder url = new StringBuilder();
		url.append(urlSetting.getMenchantService()).append("/api/merchant/merchant/list/").append(userId);

		String merchantListStr = RestHttpTemplate.get(url.toString(), headers, urlVariables);
		JSONObject merchantListJson = null;
		try {
			merchantListJson = JSON.parseObject(merchantListStr);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return result;
		}

		if (merchantListJson.containsKey("result") && "success".equals(merchantListJson.getString("result"))
				&& merchantListJson.containsKey("data")) {
			JSONObject data = merchantListJson.getJSONObject("data");

			if (data.containsKey("list")) {
				List<Merchant> merchantList = JSON.parseArray(data.getString("list"), Merchant.class);

				if (null != merchantList && !merchantList.isEmpty()) {
					for (Merchant node : merchantList) {
						result.add(node.getId());
					}
				}
			} else {
				return result;
			}
		}

		return result;
	}

	public List<Long> getMerchantRootIdsByRequest() {
//		List<Long> result = new ArrayList<Long>();
//
//		String userId = this.getMngrId();
//		if (null == userId || "".equals(userId)) {
//			return result;
//		}
//
//		UrlSetting urlSetting = ApplicationContextHolder.getBean(UrlSetting.class);
//
//		// 调用根据用户id获取商户列表接口
//		HttpHeaders headers = new HttpHeaders();
//		String subSystemCode = "";
//		try {
//			subSystemCode = this.getSubSystemCode();
//			if(null != subSystemCode && subSystemCode.endsWith("_")){
//				subSystemCode = subSystemCode.substring(0, subSystemCode.lastIndexOf("_"));
//			}
//		} catch (Exception e1) {
//			logger.error(e1.getMessage(),e1);
//		}
//		if(!"".equals(subSystemCode) && null != subSystemCode){
//			headers.add("subSystemCode", subSystemCode);
//		}
//		Map<String, Object> urlVariables = new HashMap<String, Object>();
//		StringBuilder url = new StringBuilder();
//		url.append(urlSetting.getMenchantService()).append("/api/merchant/merchant/children/").append(userId);
//		logger.info("***********************************userinfo="+url.toString());
//		logger.info("***********************************subSystemCode="+subSystemCode);
//		String merchantListStr = RestHttpTemplate.get(url.toString(), headers, urlVariables);
//		JSONObject merchantListJson = null;
//		try {
//			merchantListJson = JSON.parseObject(merchantListStr);
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//			return result;
//		}
//
//		if (merchantListJson.containsKey("result") && "success".equals(merchantListJson.getString("result"))
//				&& merchantListJson.containsKey("data")) {
//			JSONArray data = merchantListJson.getJSONArray("data");
//
//			if (data.size()>0) {
//				List<Merchant> merchantList = JSON.parseArray(data.toJSONString(), Merchant.class);
//
//				if (null != merchantList && !merchantList.isEmpty()) {
//					for (Merchant node : merchantList) {
//						result.add(node.getId());
//					}
//				}
//			} else {
//				return result;
//			}
//		}
//
//		return result;
		
		List<Long> result = new ArrayList<Long>();
		List<Merchant> merchants = this.getRootMerchantsByRequest();
		if(null != merchants && !merchants.isEmpty()){
			for(Merchant node : merchants){
				result.add(node.getId());
			}
		}
		
		return result;
	}
	
	public List<Merchant> getRootMerchantsByRequest() {
		List<Merchant> result = new ArrayList<Merchant>();

		String userId = this.getMngrId();
		if (null == userId || "".equals(userId)) {
			return result;
		}

		UrlSetting urlSetting = ApplicationContextHolder.getBean(UrlSetting.class);

		// 调用根据用户id获取商户列表接口
		HttpHeaders headers = new HttpHeaders();
		String subSystemCode = "";
		try {
			subSystemCode = this.getSubSystemCode();
			if(null != subSystemCode && subSystemCode.endsWith("_")){
				subSystemCode = subSystemCode.substring(0, subSystemCode.lastIndexOf("_"));
			}
		} catch (Exception e1) {
			logger.error(e1.getMessage(),e1);
		}
		if(!"".equals(subSystemCode) && null != subSystemCode){
			headers.add("subSystemCode", subSystemCode);
		}
		Map<String, Object> urlVariables = new HashMap<String, Object>();
		StringBuilder url = new StringBuilder();
		url.append(urlSetting.getMenchantService()).append("/api/merchant/merchant/children/").append(userId);
		logger.info("***********************************userinfo="+url.toString());
		logger.info("***********************************subSystemCode="+subSystemCode);
		String merchantListStr = RestHttpTemplate.get(url.toString(), headers, urlVariables);
		JSONObject merchantListJson = null;
		try {
			merchantListJson = JSON.parseObject(merchantListStr);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return result;
		}

		if (merchantListJson.containsKey("result") && "success".equals(merchantListJson.getString("result"))
				&& merchantListJson.containsKey("data")) {
			JSONArray data = merchantListJson.getJSONArray("data");

			if (data.size()>0) {
				List<Merchant> merchantList = JSON.parseArray(data.toJSONString(), Merchant.class);

				if (null != merchantList && !merchantList.isEmpty()) {
					for (Merchant node : merchantList) {
						result.add(node);
					}
				}
			} else {
				return result;
			}
		}

		return result;
	}
}